<?php
require_once __DIR__ . '/../config.php';

// Create a new post
function create_post($title, $content, $format = 'html') {
    if (!in_array($format, ALLOWED_FORMATS)) {
        throw new Exception('Invalid file format');
    }

    $slug = strtolower(str_replace(' ', '-', $title));
    $filename = date('Y-m-d') . '-' . $slug . '.' . $format;
    $filepath = POSTS_DIR . '/' . $filename;

    if (file_exists($filepath)) {
        throw new Exception('Post already exists');
    }

    $data = [
        'title' => $title,
        'content' => $content,
        'created_at' => date('Y-m-d H:i:s')
    ];

    file_put_contents($filepath, json_encode($data));
    return $filename;
}

// Get all posts
function get_posts() {
    $posts = [];
    $files = glob(POSTS_DIR . '/*.{html,md,txt}', GLOB_BRACE);
    
    foreach ($files as $file) {
        $content = file_get_contents($file);
        $data = json_decode($content, true);
        $data['filename'] = basename($file);
        $posts[] = $data;
    }

    // Sort by creation date (newest first)
    usort($posts, function($a, $b) {
        return strtotime($b['created_at']) - strtotime($a['created_at']);
    });

    return $posts;
}

// Get a single post by filename
function get_post($filename) {
    $filepath = POSTS_DIR . '/' . $filename;
    
    if (!file_exists($filepath)) {
        return null;
    }

    $content = file_get_contents($filepath);
    $data = json_decode($content, true);
    $data['filename'] = $filename;
    
    return $data;
}

// Render template with data
function render_template($template, $data = []) {
    extract($data);
    include "templates/$template.php";
}

// Sanitize input
function sanitize_input($data, $preserve_html = false) {
    $data = trim($data);
    $data = stripslashes($data);
    if (!$preserve_html) {
        $data = htmlspecialchars($data);
    }
    return $data;
}
